<template>
  <view class="order-hall-container">
    <scroll-view scroll-y class="content-area" @scrolltolower="loadMore" :scroll-top="scrollTop" refresher-enabled
      :refresher-triggered="refreshing" @refresherrefresh="onRefresh">
      <view class="card-list">
        <view v-for="(item, index) in orders" :key="index" class="order-card">
          <view class="card-main" @click="gotoDetail(item)">
            <view class="oil-block">
              <view class="oil-icon">
                <img :src="item.goods_image" mode="aspectFill" style="width: 180rpx;height: 180rpx;"/>
              </view>

            </view>

            <view class="info-block">
              <view class="title-row" v-if="item.franchise">
                <text class="title">{{ item.goods_name }}</text>
                <text class="link">加盟</text>
              </view>

              <view class="meta-row"><text class="label">用油量：</text><text class="value">{{ item.usage }}升</text></view>
              <view class="meta-row"><text class="label">下单时间：</text><text class="value">{{
                formatDateTime(item.order_time) }}</text></view>
              <view class="meta-row"><text class="label">用油时间：</text><text class="value">{{
                formatDateTime(item.use_time) }}</text></view>
            </view>
          </view>

          <view class="action-row" v-if="item.status === 'pending'">
            <uv-button text="去接单" size="large" :custom-style="acceptBtnStyle" @click="onAccept(item)" />
          </view>
        </view>

        <view v-if="loading" class="loading-container">
          <text class="loading-text">加载中...</text>
        </view>

        <view v-if="!hasMore && orders.length > 0" class="no-more-container">
          <text class="no-more-text">没有更多数据了</text>
        </view>

        <view v-if="!loading && orders.length === 0" class="empty-container">
          <text class="empty-text">暂无订单数据</text>
        </view>
      </view>
    </scroll-view>

    <view class="tabbar-container">
      <DriverTabBar />
    </view>
  </view>
</template>

<script setup lang="ts">
import DriverTabBar from '@/components/tabbar/DriverTabBar.vue'
import { ref, onMounted, onUnmounted } from 'vue'
import { formatDateTime } from '@/utils/dateTime'
import { UserInfoManager } from '@/utils/userInfo'
import { useRequest } from '@/api'
const { API_ORDER_HALL_POST, API_JIDAN_GET } = useRequest()
const orders = ref([])
const total = ref(0)
const loading = ref(false)
const hasMore = ref(true)
const scrollTop = ref(0)
const refreshing = ref(false)
const gotoDetail = (item) => {
  uni.navigateTo({ url: '/driver/orderHall/orderDetails?id=' + item.id })
}
const acceptBtnStyle = {
  width: '100%',
  height: '88rpx',
  borderRadius: '12rpx',
  backgroundColor: '#FF6B35',
  color: '#fff',
  fontSize: '30rpx',
  fontWeight: '600'
}

const onAccept = async (item: any) => {
  const params = {
    isdriver: UserInfoManager.lastrole(),
    id: item.id
  }
  const res = await API_JIDAN_GET(params)
  if (res.code === 1) {
    uni.reLaunch({
      url: '/driver/orderManage/index'
    })
  }
}

const onJoin = () => {
  uni.showToast({ title: '加盟入口', icon: 'none' })
}
const latitude = ref(39.908823)
const longitude = ref(116.39747)
const getCurrentLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    success: (res) => {
      latitude.value = res.latitude
      longitude.value = res.longitude
      getList1()
      uni.showToast({
        title: '位置获取成功',
        icon: 'success'
      })
    },
    fail: (err) => {
      uni.showToast({
        title: '位置获取失败',
        icon: 'none'
      })
    }
  })
}
const page = ref(1)
const getList1 = async (isLoadMore = false) => {
  if (loading.value) return

  loading.value = true

  try {
    const params = {
      lng: longitude.value,
      lat: latitude.value,
      isdriver: UserInfoManager.lastrole(),
      page: page.value,
      page_size: 10
    }

    const res = await API_ORDER_HALL_POST(params)
    if (res.code === 1) {
      if (res.data.data.length > 0) {
        res.data.data.forEach((item) => {
          item.title = item.goods_name.substring(0, 2)
        })

        if (isLoadMore) {
          orders.value = [...orders.value, ...res.data.data]
        } else {
          orders.value = res.data.data
        }

        total.value = res.data.total
        hasMore.value = orders.value.length < res.data.total
      } else {
        if (!isLoadMore) {
          orders.value = []
        }
        hasMore.value = false
      }
    }
  } catch (error) {

  } finally {
    loading.value = false
  }
}

const loadMore = () => {
  if (!hasMore.value || loading.value) return

  page.value++
  getList1(true)
}

const refresh = () => {
  page.value = 1
  hasMore.value = true
  getList1(false)
}

const onRefresh = async () => {
  refreshing.value = true
  page.value = 1
  hasMore.value = true
  await getList1(false)
  refreshing.value = false
}
onMounted(() => {
  getCurrentLocation()
  uni.$on('refreshOrderList', () => {
    setTimeout(() => {
      refresh()
    }, 200)
  })
})

onUnmounted(() => {
  uni.$off('refreshOrderList')
})
</script>

<style lang="scss" scoped>
.order-hall-container {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 使用 scroll-view 以免数据多时遮挡，并留出底部安全空间 */
.content-area {
  flex: 1;
  padding: 20rpx 0;
  /* 横向内边距移到 .card-list，保证左右一致 */
  padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
}

.card-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
  padding: 0 24rpx;
  /* 左右相同间距 */
}

.order-card {
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.06);
  padding: 24rpx;
}

.card-main {
  display: flex;
  align-items: stretch;
  gap: 20rpx;
}

.oil-block {
  width: 180rpx;
  height: 180rpx;
  background: #fff5f0;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.oil-icon {
  margin-bottom: 12rpx;
}

.oil-tag {
  font-size: 48rpx;
  font-weight: 800;
  color: #1f1f1f;
}

.info-block {
  flex: 1;
}

.title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12rpx;
}

.title {
  font-size: 34rpx;
  font-weight: 700;
  color: #1f1f1f;
}

.link {
  font-size: 28rpx;
  color: #1677ff;
}

.meta-row {
  margin: 10rpx 0;
}

.label {
  font-size: 28rpx;
  color: #8c8c8c;
}

.value {
  font-size: 28rpx;
  color: #1f1f1f;
}

.action-row {
  margin-top: 20rpx;
}

.tabbar-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 999;
  background: #fff;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}

.loading-container,
.no-more-container,
.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40rpx 0;
}

.loading-text,
.no-more-text,
.empty-text {
  font-size: 28rpx;
  color: #999;
}

.loading-text {
  color: #ff6b35;
}
</style>
